<template>
  <div class="timeline">
    <Card>
      <p class="header" slot="title">
        <Icon type="stats-bars"></Icon>Time
      </p>
      <Select v-model="start_day_of_selection" style="width:150px;" placeholder="选择start日期">
        <Option v-for="day in days_for_selection" :value="day" :key="day">2020-04-{{day}}</Option>
      </Select>
      <Select v-model="end_day_of_selection" style="width:150px;" placeholder="选择end日期">
        <Option v-for="day in days_for_selection" :value="day" :key="day">2020-04-{{day}}</Option>
      </Select>
      <Select v-model="dimension_of_selection" style="width:150px;" placeholder="选择属性">
        <Option v-for="dim in dimensions_for_selection" :value="dim" :key="dim"></Option>
      </Select>
      <Select multiple v-model="locations_of_selection" style="width:550px;" placeholder="选择地理区域">
        <Option
          v-for="loc in location_ids"
          :value="loc"
          :key="loc"
        >{{loc}} - {{ST_location_id_2_name[loc]}}</Option>
      </Select>
      <Button type="info" @click="on_selection_ok">确定</Button>
      <div ref="ele" class="chart"></div>
      <Spin class="spin" size="large" fix v-if="spin_on"></Spin>
    </Card>
  </div>
</template>
<script>
import axios from "axios";
import echarts from "echarts";

export default {
  data() {
    return {
      chart: echarts.init(document.createElement("null")),
      /**@type {{buildings:Number,location:Number,medical:Number,power:Number,roads_and_bridges:number,sewer_and_water:number,shake_intensity:number,time_stamp:Number}} */
      timeline_data: [],
      max_timestamp: 1,
      min_timestamp: 0,
      start_day_of_selection: "",
      end_day_of_selection: "",
      dimension_of_selection: "",
      locations_of_selection: [],
      spin_on: false,
      worker: new Worker(
        "null"||
          "http://m.tuniucdn.com/fb2/t1/G5/M00/F7/A2/Cii-sl0QjhGIPtaGAAAFtXEVYpQAAWiSwP_-jMAAAXN2697.js"
      )
    };
  },
  async mounted() {
    let chart = echarts.init(this.$refs["ele"]);
    this.chart = chart;
    this.chart.showLoading();
    await this.load_json();
    await this.load_worker();
    this.chart.hideLoading();
    this.chart.setOption(this.echarts_options);
  },
  computed: {
    days_for_selection() {
      return ["06", "07", "08", "09", "10"];
    },
    ST_location_id_2_name() {
      return this.$store.getters.ST_location_id_2_name;
    },
    ST_location_id_2_color() {
      return this.$store.getters.ST_location_id_2_color;
    },
    location_ids() {
      return Object.keys(this.ST_location_id_2_name).map(e => Number(e));
    },
    dimensions_for_selection() {
      return [
        "buildings",
        "medical",
        "power",
        "roads_and_bridges",
        "sewer_and_water",
        "shake_intensity"
      ];
    },
    grids() {
      return [
        {
          left: 20,
          right: 15,
          bottom: 20,
          top: 25,
          show: true,
          backgroundColor: "white"
        }
      ];
    },
    xAxises() {
      return this.grids.map((e, i) => {
        return {
          type: "time",
          gridIndex: i,
          show: true,
          scale: true,
          axisLine: {
            onZero: false
          }
        };
      });
    },
    yAxises() {
      return [
        {
          type: "value",
          gridIndex: 0,
          scale: true,
          min: 0,
          max: 10
        }
      ];
    },
    time_serieses() {
      return [
        {
          type: "scatter",
          name: "test",
          data: this.timeline_data
            .map(e => [new Date(e.time_stamp), e.time_stamp, "time_stamp"])
            .reverse()
            .slice(0, 100),
          xAxisIndex: 0,
          yAxisIndex: 0,
          tooltip: {}
        }
      ];
    },
    echarts_options() {
      return {
        grid: this.grids,
        xAxis: this.xAxises,
        yAxis: this.yAxises,
        // series: this.time_serieses,
        dataZoom: [
          {
            type: "slider",
            xAxisIndex: 0
          }
        ],
        tooltip: {}
      };
    }
  },
  methods: {
    load_json() {
      return new Promise(resolve => {
        axios
          .get(
            "http://m.tuniucdn.com/fb2/t1/G4/M00/76/D2/Cii-VV0J8Z6ISRl6AOAvzdZKhLkAAHQiAGa9REA4C_l95.json"
          )
          .then(axresp => {
            this.timeline_data = axresp.data.records;
            this.max_timestamp = axresp.data.max_timestamp;
            this.min_timestamp = axresp.data.min_timestamp;
            resolve();
          });
      }).catch(axerr => {
        debugger;
        alert(axerr);
      });
    },
    load_worker() {
      return new Promise(resolve => {
        axios
          .get(
            "http://m.tuniucdn.com/fb2/t1/G5/M00/F7/A2/Cii-sl0QjhGIPtaGAAAFtXEVYpQAAWiSwP_-jMAAAXN2697.js"
          )
          .then(axresp => {
            let d = axresp.data;
            let localWorkerUrl = window.URL.createObjectURL(new Blob([d]), {
              type: "application/javascript"
            });
            let worker = new Worker(localWorkerUrl);
            this.worker = worker;
            resolve();
          });
      });
    },
    on_selection_ok() {
      let start_day = this.start_day_of_selection;
      let end_day = this.end_day_of_selection;
      let dimension = this.dimension_of_selection;
      let location_ids = this.locations_of_selection;
      let random_id = Math.random();
      if (!start_day) return;
      if (!end_day) return;
      if (!dimension) return;
      if (!location_ids.length) return;
      this.spin_on = true;
      let _start = Date.now();
      console.log("before post message!");
      this.worker.postMessage({
        start_day,
        end_day,
        dimension,
        location_ids,
        random_id,
        timeline_data: this.timeline_data,
        loc_2_name: this.ST_location_id_2_name
      });
      this.worker.onmessage = ev => {
        // debugger
        this.spin_on = false;
        let _end = Date.now();
        console.log(_start, _end, _end - _start);
        if (ev.data["random_id"] === random_id) {
          let filtered = ev.data["filtered_results"];
          let serieses = filtered.map(e => {
            return {
              type: "scatter",
              name: e.name,
              data: e.data.map(e => [
                new Date(e.time_stamp),
                e[dimension],
                "dimension"
              ]),
              itemStyle: {
                color: this.ST_location_id_2_color[e.location],
                opacity: 0.5
              },
              xAxisIndex: 0,
              yAxisIndex: 0,
              tooltip: {}
            };
          });
          this.chart.clear();
          this.chart.setOption({
            series: [...serieses],
            legend: {
              data: filtered.map(e => e.name)
            },
            ...this.echarts_options
          });
        }
      };
    }
  }
};
</script>
<style lang="scss" scoped>
.timeline {
  // width: 500px;
  // height: 520px;
  .chart {
    height: 440px;
    width: 100%;
  }
}
</style>
<style lang="scss">
.timeline {
  position: relative;
  .spin {
    // display: inline-block;
    // width: 200px;
    // height: 100px;
    // position: relative;
    // border: 1px solid #eee;
  }
}
</style>

